package org.van.blog.controller.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.van.blog.constant.ErrorConstant;
import org.van.blog.constant.Types;
import org.van.blog.controller.BaseController;
import org.van.blog.dto.cond.MetaCond;
import org.van.blog.exception.BusinessException;
import org.van.blog.model.MetaDomain;
import org.van.blog.service.meta.MetaService;
import org.van.blog.utils.APIResponse;

@Controller
@RequestMapping("/admin/links")
public class LinksController extends BaseController {

    @Autowired
    private MetaService metaService;

    @GetMapping(value = "")
    public String index(HttpServletRequest request) {
        MetaCond metaCond = new MetaCond();
        metaCond.setType(Types.LINK.getType());
        List<MetaDomain> metas = metaService.getMetas(metaCond);
        request.setAttribute("links", metas);
        return "admin/links";
    }

    @PostMapping(value = "/save")
    @ResponseBody
    public APIResponse<?> addLink(
            @RequestParam(name = "title", required = true) String title,
            @RequestParam(name = "url", required = true) String url,
            @RequestParam(name = "logo", required = false) String logo,
            @RequestParam(name = "mid", required = false) Integer mid,
            @RequestParam(name = "sort", required = false, defaultValue = "0") int sort) {
        try {
            MetaDomain meta = new MetaDomain();
            meta.setName(title);
            meta.setSlug(url);
            meta.setDescription(logo);
            meta.setSort(sort);
            meta.setType(Types.LINK.getType());
            if (null != mid) {
                meta.setMid(mid);
                metaService.updateMeta(meta);
            } else {
                metaService.addMea(meta);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw BusinessException.withErrorCode(ErrorConstant.Meta.ADD_META_FAIL);
        }

        return APIResponse.success();
    }

    @PostMapping(value = "/delete")
    @ResponseBody
    public APIResponse<?> deleteLink(
            @RequestParam(name = "mid", required = true) int mid) {
        try {
            metaService.deleteMetaById(mid);
        } catch (Exception e) {
            e.printStackTrace();
            throw BusinessException.withErrorCode(ErrorConstant.Meta.DELETE_META_FAIL);
        }

        return APIResponse.success();
    }

}
